import axios from ''
import store from '@/store'
import { getToken,getTenantKey ,getTID} from '@/utils/auth'

const config = require('./config')
const baseURL = config[process.env.NODE_ENV].baseUrl

const CancelToken = axios.CancelToken
const pendingReq = {}

// 创建一个axios实例
const service = axios.create({
  baseURL,
  // withCredentials: true, //跨域请求是否提供凭据信息(cookie、HTTP认证及客户端SSL证明等),当配置了xhr.withCredentials = true时，必须在后端增加 response 头信息Access-Control-Allow-Origin，且必须指定域名，而不能指定为*。
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      // JWT鉴权
      config.headers.Authorization = getToken()
      config.headers.TenantKey = getTenantKey()
      config.headers.TID = getTID();
      // 取消请求
      // const key = config.url + '&' + config.method
      // pendingReq[key] && pendingReq[key]('操作太频繁了~')
      // config.cancelToken = new CancelToken(c => {
      //   pendingReq[key] = c
      // })
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    sessionStorage.setItem(
      'Content-Disposition',
      response.headers['content-disposition']
    )
    const res = response.data
    // 取消请求
    const key = response.config.url + '&' + response.config.method
    pendingReq[key] && delete pendingReq[key]

    // 与后端约定的错误码
    if (res.code !== 200) {
      console.log('接口请求出错')
      // return Promise.reject(new Error(res.message || 'Error'))
    }
    return res
  },
  error => {
    // http请求异常统一处理
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误'
          break
        case 401:
          error.message = '未授权，请登录'
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器内部错误'
          break
        case 501:
          error.message = '服务未实现'
          break
        case 502:
          error.message = '网关错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网关超时'
          break
        case 505:
          error.message = 'HTTP版本不受支持'
          break
        default:
          break
      }
    }
    return Promise.reject(error)
  }
)

export default service
